<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Illuminate\Support\Facades\DB;

class MqData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mq:data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
        $this->channel = $this->connection->channel();
        $this->channel->queue_declare('logs', false, false, false, false);
        //$this->channel->exchange_declare('logs','fanout',false,false,false);
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $callback = function($msg){

            $s = json_decode($msg->body,true);

            if($s){

                $date['code'] = $s['code'];
                //print_r($date);
                //foreach ($s as $key => $value) {
                //DB::table('area')->insert($date);
                echo 1;
                //     $str = substr($value['0'],-4);
                //  $str1 = substr($value['0'],4,5);
                // echo $str;
                // print_r($data);
                //  if($str=='0000'){
                //  echo 1;
                //  $sql ="UPDATE area set level=1  WHERE code=".$value['0'];
                //  $DB->new_query($sql);
                //  continue ;
                // }
                // if($str1=='00'){
                //  $sql ="UPDATE area set level=2  WHERE code=".$value['0'];
                //  $DB->new_query($sql);
                //   echo 2;
                //  continue ;
                //  }
                //  $sql ="UPDATE area set level=3  WHERE code=".$value['0'];
                //  $DB->new_query($sql);
                    
                //}
            }
            

            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        };

        $this->channel->basic_qos(null, 1, null);
        $this->channel->basic_consume('logs', '', false, false, false, false, $callback);

        while(count($this->channel->callbacks)) {
            $this->channel->wait();
        }

        $this->channel->close();
        $this->connection->close();
    }
}
